/*
 * Copyright (C) 2020 Jimmy Hogoboom
 *
 * This file is part of Limitlist.
 *
 * Limitlist is free software: you can redistribute it and/or modify
 * it under the terms of the Affero GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Limitlist is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Affero GNU General Public License for more details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * along with Limitlist.  If not, see <https://www.gnu.org/licenses/>.
 */

// SPDX-License-Identifier: AGPL-3.0-or-later

export const calculateTotal = (price: string, quantity: string) => {
  if (!price || !quantity) return '';

  const priceNumber = Number(price.replace('$', ''));
  const quantityNumber = Number(quantity);

  if (!priceNumber || !quantityNumber) return '0';

  return (priceNumber * quantityNumber).toFixed(2);
};

export const arrayMoveMutate = (array: any[], from: number, to: number) => {
	const startIndex = to < 0 ? array.length + to : to;
	const item = array.splice(from, 1)[0];
	array.splice(startIndex, 0, item);
};

export const arrayMove = (array: any[], from: number, to: number) => {
	array = array.slice();
	arrayMoveMutate(array, from, to);
	return array;
};

export const currencyLabel = (value: string) =>
  value && !isNaN(Number(value))
    ? `$${Number(value).toFixed(2)}`
    : '';
